package com.mmall.controller.portal;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.demo.trade.config.Configs;
import com.google.common.collect.Maps;
import com.mmall.common.Const;
import com.mmall.common.ResponseCode;
import com.mmall.common.ServerResponse;
import com.mmall.pojo.User;
import com.mmall.service.IOrderService;
import com.mmall.utils.CookieUtil;
import com.mmall.utils.JsonUtil;
import com.mmall.utils.RedisPoolUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Iterator;
import java.util.Map;

@Controller
@RequestMapping("/order")
public class OrderController {

    private static final Logger logger = LoggerFactory.getLogger(OrderController.class);

    @Autowired
    private IOrderService iOrderService;

    /**创建订单
     * @param request
     * @param shippingId
     * @return
     */
    @RequestMapping("create")
    @ResponseBody
    public ServerResponse create(HttpServletRequest request, Integer shippingId) {
        String loginToken = CookieUtil.readLoginToken(request);
        if (StringUtils.isEmpty(loginToken)) {
            return ServerResponse.retErrorMsg("用户未登录，无法获取信息");
        }
        String userJsonStr = RedisPoolUtil.get(loginToken);
        User user = JsonUtil.stringToObj(userJsonStr, User.class);
        if (user == null) {
            return ServerResponse.retErrorCode(ResponseCode.NEED_LOGIN.getCode(), "用户未登录,请登录");
        }
        return iOrderService.createOrder(user.getId(), shippingId);
    }


    /**取消订单
     * @param request
     * @param orderNo
     * @return
     */
    @RequestMapping("cancel")
    @ResponseBody
    public ServerResponse cancel(HttpServletRequest request, Long orderNo) {
        String loginToken = CookieUtil.readLoginToken(request);
        if (StringUtils.isEmpty(loginToken)) {
            return ServerResponse.retErrorMsg("用户未登录，无法获取信息");
        }
        String userJsonStr = RedisPoolUtil.get(loginToken);
        User user = JsonUtil.stringToObj(userJsonStr, User.class);
        if (user == null) {
            return ServerResponse.retErrorCode(ResponseCode.NEED_LOGIN.getCode(), "用户未登录,请登录");
        }
        return iOrderService.cancel(user.getId(), orderNo);
    }

    /**查询购物车中产品
     * @param request
     * @return
     */
    @RequestMapping("getOrderProduct")
    @ResponseBody
    public ServerResponse getOrderProduct(HttpServletRequest request) {
        String loginToken = CookieUtil.readLoginToken(request);
        if (StringUtils.isEmpty(loginToken)) {
            return ServerResponse.retErrorMsg("用户未登录，无法获取信息");
        }
        String userJsonStr = RedisPoolUtil.get(loginToken);
        User user = JsonUtil.stringToObj(userJsonStr, User.class);
        if (user == null) {
            return ServerResponse.retErrorCode(ResponseCode.NEED_LOGIN.getCode(), "用户未登录,请登录");
        }
        return iOrderService.getOrderCartProduct(user.getId());
    }

    /**订单详情
     * @param request
     * @return
     */
    @RequestMapping("detail")
    @ResponseBody
    public ServerResponse detail(HttpServletRequest request, Long orderNo) {
        String loginToken = CookieUtil.readLoginToken(request);
        if (StringUtils.isEmpty(loginToken)) {
            return ServerResponse.retErrorMsg("用户未登录，无法获取信息");
        }
        String userJsonStr = RedisPoolUtil.get(loginToken);
        User user = JsonUtil.stringToObj(userJsonStr, User.class);
        if (user == null) {
            return ServerResponse.retErrorCode(ResponseCode.NEED_LOGIN.getCode(), "用户未登录,请登录");
        }
        return iOrderService.getOrderDetail(user.getId(), orderNo);
    }


    /**订单列表
     * @param request
     * @param pageNum
     * @param pageSize
     * @return
     */
    @RequestMapping("list")
    @ResponseBody
    public ServerResponse list(HttpServletRequest request,
                               @RequestParam(value = "pageNum",defaultValue = "1") int pageNum,
                               @RequestParam(value = "pageSize",defaultValue = "10") int pageSize) {
        String loginToken = CookieUtil.readLoginToken(request);
        if (StringUtils.isEmpty(loginToken)) {
            return ServerResponse.retErrorMsg("用户未登录，无法获取信息");
        }
        String userJsonStr = RedisPoolUtil.get(loginToken);
        User user = JsonUtil.stringToObj(userJsonStr, User.class);
        if (user == null) {
            return ServerResponse.retErrorCode(ResponseCode.NEED_LOGIN.getCode(), "用户未登录,请登录");
        }
        return iOrderService.getOrderList(user.getId(),pageNum,pageSize);
    }

    /**订单支付的方法
     * @param orderNo
     * @param request
     * @return
     */
    @RequestMapping("pay")
    @ResponseBody
    public ServerResponse pay(Long orderNo, HttpServletRequest request) {
        String loginToken = CookieUtil.readLoginToken(request);
        if (StringUtils.isEmpty(loginToken)) {
            return ServerResponse.retErrorMsg("用户未登录，无法获取信息");
        }
        String userJsonStr = RedisPoolUtil.get(loginToken);
        User user = JsonUtil.stringToObj(userJsonStr, User.class);
        if (user == null) {
            return ServerResponse.retErrorCode(ResponseCode.NEED_LOGIN.getCode(), "用户未登录,请登录");
        }
        String path = request.getSession().getServletContext().getRealPath("upload");

        return iOrderService.pay(orderNo, user.getId(), path);
    }

    /**支付宝回调方法
     * @param request
     * @return
     */
    @RequestMapping("alipayCallback")
    @ResponseBody
    public Object alipayCallback(HttpServletRequest request) {
        Map requestParams = request.getParameterMap();

        Map<String,String> params = Maps.newHashMap();
        for(Iterator iter = requestParams.keySet().iterator(); iter.hasNext();){
            String name = (String)iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for(int i = 0 ; i <values.length;i++){

                valueStr = (i == values.length -1)?valueStr + values[i]:valueStr + values[i]+",";
            }
            params.put(name,valueStr);
        }
        logger.info("支付宝回调,sign:{},trade_status:{},参数:{}",params.get("sign"),params.get("trade_status"),params.toString());

        //非常重要,验证回调的正确性,是不是支付宝发的.并且呢还要避免重复通知.
        params.remove("sign_type");
        try {
            boolean alipayRSACheckedV2 = AlipaySignature.rsaCheckV2(params,
                    Configs.getAlipayPublicKey(),"utf-8",Configs.getSignType());
            if (!alipayRSACheckedV2) {
                return ServerResponse.retSuccessMsg("非法请求");
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }

        //验证等
        ServerResponse serverResponse = iOrderService.aliCallback(params);
        if (serverResponse.isSuccess()) {
            return Const.AlipayCallback.RESPONSE_SUCCESS;
        }
        return Const.AlipayCallback.RESPONSE_FAILED;
    }

    /**查询订单支付状态
     * @param orderNo
     * @param request
     * @return
     */
    @RequestMapping("queryOrderPayStatus")
    @ResponseBody
    public ServerResponse queryOrderPayStatus(Long orderNo, HttpServletRequest request) {
        String loginToken = CookieUtil.readLoginToken(request);
        if (StringUtils.isEmpty(loginToken)) {
            return ServerResponse.retErrorMsg("用户未登录，无法获取信息");
        }
        String userJsonStr = RedisPoolUtil.get(loginToken);
        User user = JsonUtil.stringToObj(userJsonStr, User.class);
        if (user == null) {
            return ServerResponse.retErrorCode(ResponseCode.NEED_LOGIN.getCode(), "用户未登录,请登录");
        }
        ServerResponse response = iOrderService.queryOrderPayStatus(user.getId(),orderNo);
        if (response.isSuccess()) {
            return ServerResponse.retSuccessData(true);
        }
        return ServerResponse.retSuccessData(false);
    }

    public static void main(String[] args) throws Exception{
        String s = "23qwe打发士大夫";
        System.out.println(s.length());
        byte[] bytes = s.getBytes();
        for (byte aByte : bytes) {
            System.out.println(aByte);
        }
        System.out.println("bytes:"+s.getBytes().length);
        char[] c = s.toCharArray();

        for (char c1 : c) {
            if(c1>128){
                System.out.println("128c:"+c1);
            }
            System.out.println("c:"+c1);
//            System.out.println(Integer.toBinaryString(c1));
        }
        System.out.println("c.length:"+c.length);


        String a = "名";
        System.out.println("UTF-8编码长度:"+a.getBytes("UTF-8").length);
        System.out.println("GBK编码长度:"+a.getBytes("GBK").length);
        System.out.println("GB2312编码长度:"+a.getBytes("GB2312").length);
        System.out.println("==========================================");

        String cs = "0x20001";
        System.out.println("UTF-8编码长度:"+cs.getBytes("UTF-8").length);
        System.out.println("GBK编码长度:"+cs.getBytes("GBK").length);
        System.out.println("GB2312编码长度:"+cs.getBytes("GB2312").length);
        System.out.println("==========================================");

    }
}
